﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HDLogCenter.Infrastructure.Utils
{
    /// <summary>
    /// 雪花ID生成器 (静态工具类)
    /// </summary>
    public static class SnowflakeIdGenerator
    {
        private const long Twepoch = 1288834974657L; // 起始时间戳
        private const int WorkerIdBits = 5;          // 机器ID位数
        private const int DatacenterIdBits = 5;      // 数据中心位数
        private const int SequenceBits = 12;         // 序列号位数

        private const long MaxWorkerId = -1L ^ (-1L << WorkerIdBits);
        private const long MaxDatacenterId = -1L ^ (-1L << DatacenterIdBits);
        private const long SequenceMask = -1L ^ (-1L << SequenceBits);

        private const int WorkerIdShift = SequenceBits;
        private const int DatacenterIdShift = SequenceBits + WorkerIdBits;
        private const int TimestampLeftShift = SequenceBits + WorkerIdBits + DatacenterIdBits;

        private static long _lastTimestamp = -1L;
        private static long _sequence = 0L;

        private static readonly object _lock = new object();

        // 可以根据部署环境修改
        private static readonly long WorkerId = 1;
        private static readonly long DatacenterId = 1;

        static SnowflakeIdGenerator()
        {
            if (WorkerId > MaxWorkerId || WorkerId < 0)
                throw new ArgumentException($"WorkerId 必须在 0 - {MaxWorkerId} 之间");

            if (DatacenterId > MaxDatacenterId || DatacenterId < 0)
                throw new ArgumentException($"DatacenterId 必须在 0 - {MaxDatacenterId} 之间");
        }

        /// <summary>
        /// 生成下一个唯一ID
        /// </summary>
        public static long NextId()
        {
            lock (_lock)
            {
                var timestamp = TimeGen();

                if (timestamp < _lastTimestamp)
                {
                    throw new Exception($"系统时钟回拨，拒绝生成ID {_lastTimestamp - timestamp} 毫秒");
                }

                if (_lastTimestamp == timestamp)
                {
                    _sequence = (_sequence + 1) & SequenceMask;
                    if (_sequence == 0)
                    {
                        timestamp = TilNextMillis(_lastTimestamp);
                    }
                }
                else
                {
                    _sequence = 0L;
                }

                _lastTimestamp = timestamp;

                return ((timestamp - Twepoch) << TimestampLeftShift)
                       | (DatacenterId << DatacenterIdShift)
                       | (WorkerId << WorkerIdShift)
                       | _sequence;
            }
        }

        private static long TilNextMillis(long lastTimestamp)
        {
            var timestamp = TimeGen();
            while (timestamp <= lastTimestamp)
            {
                timestamp = TimeGen();
            }
            return timestamp;
        }

        private static long TimeGen()
        {
            return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
        }
    }
}
